<script setup>
    import {
        Edit,
        Delete,
        BellFilled,
        Search
    } from '@element-plus/icons-vue'
    import {onMounted, ref} from 'vue'
    // 导入 ExcelJS 库
    import ExcelJS from 'exceljs/dist/exceljs.min.js';
    //声明一个异步的函数
    import {
       ExamListBySearchService
    } from '@/api/exam.js'
    import {
        CourseListAllSerivce
    } from '@/api/course.js'
    import {
        TeacherListAllSerivce
    } from '@/api/teacher.js'
    import {
        ElMessage
    } from 'element-plus'

    const exams = ref([{
        "examId":1,
        "examGrade":"",
        "studentId":"",
        "courseId":"",
    }])
    const teachers = ref([{
        "teacherId":1,
        "teacherName":"",
        "teacherPhone":"",
        "teacherPhoto":"",
        "professionId":""
    }])
    const teacherAll = async () => {
        try {
            const result = await TeacherListAllSerivce();
            teachers.value = result.data;
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '搜索出错',
            });
        }
    }
    const courses = ref([{
        "courseId":1,
        "courseName":"",
        "courseSemester":"",
        "courseCreditHour":"",
        "teacherId":"",
        "professionId":""
    }])
    const courseAll = async () => {
        try {
            const result = await CourseListAllSerivce();
            courses.value = result.data;
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '搜索出错',
            });
        }
    }
    //分页
    const currentPage = ref(1)
    const pageSize = ref(5)
    const total = ref(20)
    const handleSizeChange = (val) => {
        pageSize.value = val;
        search();
    }
    const handleCurrentChange = (val) => {
        currentPage.value = val;
        search();
    }
    onMounted(() => {
        search();
        courseAll();
    });


    const multipleSelection = ref([])
    
    // 导出
    const exportSelected = () => {
        if (multipleSelection.value.length === 0) {
            ElMessage({
                type: 'error',
                message: '请选择要导出的数据',
            });
            return;
        }

        // 创建一个新的工作簿
        const workbook = new ExcelJS.Workbook();

        // 添加一个工作表
        const worksheet = workbook.addWorksheet('Sheet1');

        // 设置表头信息
        worksheet.addRow(['专业名称','专业类别']);

        // 获取选择的数据
        const selectedData = multipleSelection.value;

        // 将数据添加到工作表中
        selectedData.forEach(row => {
            worksheet.addRow([
                row.examName,
                row.examType
            ]);
        });

        // 将工作簿保存为Excel文件
        workbook.xlsx.writeBuffer()
            .then(buffer => {
                const blob = new Blob([buffer], {
                    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                });
                const fileName = '专业数据.xlsx';

                // 创建下载链接并触发下载
                const link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = fileName;
                link.click();

                ElMessage({
                    type: 'success',
                    message: '导出成功',
                });
            })
            .catch(error => {
                console.error('导出Excel文件时出错:', error);
                ElMessage({
                    type: 'error',
                    message: '导出失败',
                });
            });
    }
      //搜索
    const handleSelectionChange = (val) => {
        multipleSelection.value = val
    }
    const input = ref("");
    const select = ref("1");
    const search = async () => {
    try {
        const result = await ExamListBySearchService(input.value, select.value, currentPage.value, pageSize.value);
        exams.value = result.data.rows;
        total.value = result.data.total;
        // 遍历课程数据，获取对应的课程名称并添加到考试对象中
        const result1 = await CourseListAllSerivce();
        courses.value = result1.data;
        const result2 = await TeacherListAllSerivce();
        teachers.value = result2.data;
        exams.value.forEach(exam => {
            const course = courses.value.find(cou => cou.courseId === exam.courseId);
            if (course) {
                exam.courseName = course.courseName;
                exam.courseSemester = course.courseSemester;
                if(exam.examGrade === 100){ 
                    exam.courseCreditHour = course.courseCreditHour; 
                }else if(exam.examGrade >= 90){
                    exam.courseCreditHour = course.courseCreditHour * 0.9; 
                }else if(exam.examGrade >= 80){
                    exam.courseCreditHour = course.courseCreditHour * 0.8; 
                }else if(exam.examGrade >= 70){
                    exam.courseCreditHour = course.courseCreditHour * 0.7; 
                }else if(exam.examGrade >= 60){
                    exam.courseCreditHour = course.courseCreditHour * 0.6; 
                }else {
                    exam.courseCreditHour = 0;
                }
            }
            const teacher = teachers.value.find(tea => tea.teacherId === course.teacherId); // 此处应该使用 course.teacherId，而不是 exam.teacherId
            if (teacher) {
                exam.teacherName = teacher.teacherName;
            }
        });
    } catch (error) {
        ElMessage({
            type: 'error',
            message: '搜索出错',
        });
    }
}


</script>
<template>
    <div class="card-container">
        <el-card class="page-container">
            <template #header>
                <div class="header">
                    <span style="font-size: 14px;"><b>成绩查看</b></span>
                    <div class="extra">
                        <el-input v-model="input" placeholder="请输入" class="input-with-select">
                            <template #prepend>
                                <el-select v-model="select" placeholder="课程名称" style="width: 115px">
                                    <el-option label="课程名称" value="1" />
                                </el-select>
                            </template>
                            <template #append>
                                <el-button :icon="Search" @click="search(input,select,currentPage,pageSize)" />
                            </template>
                        </el-input>
                        <el-button type="success" @click="exportSelected()" plain>导出</el-button>
                    </div>
                </div>
            </template>
            <el-table :data="exams" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="序号" width="150" type="index"> </el-table-column>
                <el-table-column label="课程名称"  prop="courseName"></el-table-column>
                <el-table-column label="开设学期"  prop="courseSemester"></el-table-column>
                <el-table-column label="课程学分"  prop="courseCreditHour"></el-table-column>
                <el-table-column label="课程老师"  prop="teacherName"></el-table-column>
                <el-table-column label="分数"  prop="examGrade"></el-table-column>
                <template #empty>
                    <el-empty description="没有数据" />
                </template>
            </el-table>

        </el-card>
    </div>
    <el-pagination class="el-p" v-model:current-page="currentPage" v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]" :background="true" layout="jumper,total, sizes, prev, pager, next " :total="total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
</template>

<style lang="scss" scoped>
    .card-container {
        height: 520px;
        /* 设置合适的固定高度 */
        overflow: auto;
    }

    .page-container {
        min-height: 100%;
        box-sizing: border-box;

        .header {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .extra {
                display: flex;
                align-items: center;

                .el-input {
                    margin-right: 20px;
                }
            }
        }
    }

    .custom-date-picker {
        display: flex;
        width: 100%;
        padding: 0;
        flex-wrap: wrap;
    }

    .el-p {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
    }

    .input-with-select {
        background-color: var(--el-fill-color-blank);
    }
    // 调整样式
:deep(.ql-editor) {
  min-height: 180px;
}
:deep(.ql-formats) {
  height: 21px;
  line-height: 21px;
}

</style>